const express = require('express');
const router = express.Router();
const Post = require('../models/post');
const auth = require('../middlewares/auth');
const User = require('../models/user');
const { Op } = require('sequelize');
const Recipe = require('../models/recipe');

// 创建帖子
router.post('/posts', auth, async (req, res) => {
  try {
    const { title, content, calories, images } = req.body;
    
    // 创建帖子
    const post = await Post.create({
      title,
      content,
      calories,
      images,
      userId: req.user.id
    });

    res.status(201).json(post);
  } catch (error) {
    console.error('创建帖子失败:', error);
    res.status(500).json({ message: '创建帖子失败' });
  }
});

// 获取帖子列表
router.get('/posts', async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    const posts = await Post.findAndCountAll({
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']],
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'nickname', 'avatar']
        },
        {
          model: Recipe,
          as: 'recipe',
          required: false,
          attributes: ['id', 'name', 'nutrition']
        }
      ]
    });

    // 处理返回数据，将卡路里从 nutrition 对象中提取出来
    const formattedPosts = posts.rows.map(post => {
      const plainPost = post.get({ plain: true });
      if (plainPost.recipe) {
        plainPost.calories = plainPost.recipe.nutrition.calories;
      }
      return plainPost;
    });

    res.json({
      total: posts.count,
      posts: formattedPosts
    });
  } catch (error) {
    console.error('获取帖子列表失败:', error);
    res.status(500).json({ message: '获取帖子列表失败' });
  }
});

// 获取帖子详情
router.get('/posts/:id', async (req, res) => {
  try {
    const post = await Post.findByPk(req.params.id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'nickname', 'avatar']
        },
        {
          model: Recipe,
          as: 'recipe',
          required: false,
          attributes: [
            'id', 'name', 'description', 'ingredients', 'steps', 
            'cookingTime', 'difficulty', 'nutrition'
          ]
        }
      ]
    });

    if (!post) {
      return res.status(404).json({ message: '帖子不存在' });
    }

    // 如果用户已登录,检查是否已点赞
    let isLiked = false;
    if (req.user) {
      // TODO: 实现点赞状态检查
      // isLiked = await PostLike.findOne({
      //   where: {
      //     postId: post.id,
      //     userId: req.user.id
      //   }
      // });
    }

    res.json({
      ...post.toJSON(),
      isLiked
    });
  } catch (error) {
    console.error('获取帖子详情失败:', error);
    res.status(500).json({ message: '获取帖子详情失败' });
  }
});

// 点赞/取消点赞帖子
router.post('/posts/:id/like', auth, async (req, res) => {
  try {
    const post = await Post.findByPk(req.params.id);

    if (!post) {
      return res.status(404).json({ message: '帖子不存在' });
    }

    // TODO: 实现点赞/取消点赞逻辑
    // const liked = await PostLike.findOne({
    //   where: {
    //     postId: post.id,
    //     userId: req.user.id
    //   }
    // });

    // if (liked) {
    //   await liked.destroy();
    //   await post.decrement('likes');
    // } else {
    //   await PostLike.create({
    //     postId: post.id,
    //     userId: req.user.id
    //   });
    //   await post.increment('likes');
    // }

    // 临时实现:直接增加点赞数
    await post.increment('likes');

    res.json({ message: '操作成功' });
  } catch (error) {
    console.error('点赞操作失败:', error);
    res.status(500).json({ message: '点赞操作失败' });
  }
});

// 获取个人帖子列表
router.get('/my-posts', auth, async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    const posts = await Post.findAll({
      where: {
        userId: req.user.id
      },
      include: [{
        model: User,
        as: 'user',
        attributes: ['id', 'nickname', 'avatar']
      }],
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    res.json({
      code: 0,
      message: '获取成功',
      data: {
        posts
      }
    });
  } catch (error) {
    console.error('获取个人帖子失败:', error);
    res.json({
      code: 1,
      message: '获取个人帖子失败'
    });
  }
});

// 删除帖子
router.delete('/posts/:id', auth, async (req, res) => {
  try {
    const post = await Post.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!post) {
      return res.json({
        code: 1,
        message: '帖子不存在或无权限删除'
      });
    }

    await post.destroy();

    res.json({
      code: 0,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除帖子失败:', error);
    res.json({
      code: 1,
      message: '删除帖子失败'
    });
  }
});

// 更新帖子
router.put('/posts/:id', auth, async (req, res) => {
  try {
    const post = await Post.findOne({
      where: {
        id: req.params.id,
        userId: req.user.id
      }
    });

    if (!post) {
      return res.json({
        code: 1,
        message: '帖子不存在或无权限修改'
      });
    }

    const { title, content, calories, images } = req.body;
    
    await post.update({
      title,
      content,
      calories,
      images
    });

    res.json({
      code: 0,
      message: '更新成功',
      data: post
    });
  } catch (error) {
    console.error('更新帖子失败:', error);
    res.json({
      code: 1,
      message: '更新帖子失败'
    });
  }
});

module.exports = router; 